package com.tdk.mybatisplus.demo.common.util;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.tdk.mybatisplus.demo.common.entity.Constants;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 日期转换
 * </p>
 *
 * @author: taodingkai
 * @modified:
 * @since: 2022/5/24 11:59 
 */
@Slf4j
public class SqlDateStringConverter implements Converter<Date> {

  @Override
  public Class<Date> supportJavaTypeKey() {
    return Date.class;
  }

  @Override
  public CellDataTypeEnum supportExcelTypeKey() {
    return CellDataTypeEnum.STRING;
  }

  @Override
  public Date convertToJavaData(
      ReadCellData<?> cellData,
      ExcelContentProperty excelContentProperty,
      GlobalConfiguration globalConfiguration) throws Exception {
    return strToDate(cellData.getStringValue());
  }

  @Override
  public WriteCellData<?> convertToExcelData(
      Date value, ExcelContentProperty contentProperty,
      GlobalConfiguration globalConfiguration) {
    return new WriteCellData<String>(DateUtil.format(value, Constants.DATE_PATTERN));
  }

  /**
   * 字符串转日期
   *
   * @param strDate 字符串
   */
  public static Date strToDate(String strDate) {
    String           str    = strDate;
    SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_TIME_PATTERN);
    java.util.Date   d      = null;
    try {
      d = format.parse(str);
    } catch (Exception e) {
      log.error("时间转换失败", e);
    }
    if (Objects.nonNull(d)) {
      return new Date(d.getTime());
    }
    return null;
  }

}
